package hengtiansoft.com.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by lu on 16/2/1.
 */
public class Bluetoolth extends BaseActivity {
    private BluetoothDevice remoteDevice = null;
    BluetoothAdapter bluetoothAdapter;
    TextView textView;
    Set<BluetoothDevice> pairedDevices;
    List<myB> bs = new ArrayList<>();
    String bluetoothMsg = "";
    ListAdapter stringAdapter;
    String contentblue;
    AlertDialog.Builder dialog;

    private class myB {
        String name;
        String address;

        public myB(String name, String address) {
            this.name = name;
            this.address = address;
        }

        public String getName() {
            return name;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 发现设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 从Intent中获取设备对象
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 将设备名称和地址放入array bluetoothAdapter，以便在ListView中显示
//                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                bs.add(new myB(device.getName(), device.getAddress()));
//                textView.setText(device.getName() + "\n" + device.getAddress());
                if (bs.size() > 0) {
                    int i = 0;
                    while (i < bs.size()) {
                        bluetoothMsg = bluetoothMsg + bs.get(i).getName() + bs.get(i).getAddress();
                        i++;
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.bluetooth);
        super.onCreate(savedInstanceState);
        // 注册BroadcastReceiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothAdapter.enable();
    }

    public void initView() {
        textView = (TextView) findViewById(R.id.bluetooth);
        findViewById(R.id.searchs).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bs.clear();
                bluetoothAdapter.startDiscovery();
                if (bluetoothAdapter == null) {
                    //未打开蓝牙
                    Log.e("lu", "未打开蓝牙");
                    return;
                }
//                if (!bluetoothAdapter.isEnabled()) {
//                    bluetoothAdapter.enable();
//                    bluetoothAdapter.cancelDiscovery();
//                    bluetoothAdapter.startDiscovery();
//                }
            }
        });
        findViewById(R.id.around).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.v("lu", "" + bs.size());
                bluetoothMsg = "";
                int i = 0;
                while (i < bs.size()) {
                    bluetoothMsg = bluetoothMsg + bs.get(i).getName() + ",";
//                    bs.get(i).getAddress();
                    Log.e("lubs", bs.get(i).getName() + bs.get(i).getAddress());
                    i++;
                }
                if (bluetoothMsg.equals("")) {
                    bluetoothMsg = "未找到蓝牙设备";
                }
                textView.setText(bluetoothMsg);
            }
        });
        findViewById(R.id.content).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bluetoothAdapter.cancelDiscovery();
                //需要先关闭,保证数据不再更新,否则会报错
                stringAdapter = new ListAdapter();
                dialog = new AlertDialog.Builder(Bluetoolth.this);
                dialog.setTitle("请选择要进行配对的蓝牙");
                dialog.setSingleChoiceItems(stringAdapter, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(Bluetoolth.this, "你选择了" + bs.get(which).getName(), Toast.LENGTH_SHORT).show();
                        contentblue = bs.get(which).getAddress();
                    }
                });
                dialog.setPositiveButton("true", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //// TODO: 16/4/1
                        if (contentblue.equals("")) {
                            Toast.makeText(Bluetoolth.this, "地址不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (pair(contentblue, "123456")) {
                            Toast.makeText(Bluetoolth.this, "已发送", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                dialog.setNegativeButton("clean", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });
    }


    public void initData() {

    }


    @Override
    protected void onDestroy() {
        bluetoothAdapter.cancelDiscovery();
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    public boolean pair(String strAddr, String strPsw) {
        boolean result = false;
        //蓝牙设备适配器
        //取消发现当前设备的过程
        bluetoothAdapter.cancelDiscovery();
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();
        }
        if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) { // 检查蓝牙地址是否有效
            Log.d("mylog", "devAdd un effient!");
        }
        //由蓝牙设备地址获得另一蓝牙设备对象
        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            try {
                Log.d("mylog", "NOT BOND_BONDED");
                setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
                createBond(device.getClass(), device);
//				ClsUtils.cancelPairingUserInput(device.getClass(), device);
                remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDevice
                result = true;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("mylog", "setPiN failed!");
                e.printStackTrace();
            } //

        } else {
            Log.d("mylog", "HAS BOND_BONDED");
            try {
                //ClsUtils这个类的的以下静态方法都是通过反射机制得到需要的方法
                createBond(device.getClass(), device);//创建绑定
                setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
                createBond(device.getClass(), device);
//				ClsUtils.cancelPairingUserInput(device.getClass(), device);
                remoteDevice = device; // 如果绑定成功，就直接把这个设备对象传给全局的remoteDevice
                result = true;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("mylog", "setPiN failed!");
                e.printStackTrace();
            }
        }
        return result;
    }


    public class ListAdapter extends BaseAdapter {


        @Override
        public int getCount() {
            return bs.size();
        }

        @Override
        public Object getItem(int position) {
            return bs.get(position).getName();
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = View.inflate(Bluetoolth.this, R.layout.myitem, null);

            TextView textView = (TextView) convertView.findViewById(R.id.textView4);

            textView.setText(bs.get(position).getName());

            TextView textView1 = (TextView) convertView.findViewById(R.id.textView9);
            textView1.setText(bs.get(position).getAddress());
            return convertView;
        }
    }

    public boolean createBond(Class btClass, BluetoothDevice btDevice)
            throws Exception {
        Method createBondMethod = btClass.getMethod("createBond");
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
        return returnValue.booleanValue();
    }

    public boolean setPin(Class btClass, BluetoothDevice btDevice,
                          String str) throws Exception {
        try {
            Method removeBondMethod = btClass.getDeclaredMethod("setPin",
                    byte[].class);
            Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,
                    new Object[]
                            {str.getBytes()});
            Log.e("returnValue", "" + returnValue);
        } catch (SecurityException e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // throw new RuntimeException(e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return true;

    }
}
